package tools

import (
	"fmt"
	"log"
	"prometheus_import_consul/global"

	"github.com/hashicorp/consul/api"
)

func Add_Telegraf(ip, env, ServiceType, businesscode string) {

	telegrafID := global.Config.Consul.ServiceName[2] + "_" + ip

	// 创建服务注册的配置
	registration := &api.AgentServiceRegistration{
		ID:      telegrafID,
		Name:    global.Config.Consul.ServiceName[2],
		Address: ip,
		Tags:    []string{global.Config.Consul.ServiceName[2]},
		Meta: map[string]string{
			"ip":            ip,
			"env":           env,
			"type":          ServiceType,
			"business_code": businesscode,
		},
		Check: &api.AgentServiceCheck{
			TCP:                            fmt.Sprintf("%s:%d", ip, 9273),
			Interval:                       "15s",
			Timeout:                        "30s",
			DeregisterCriticalServiceAfter: "5m", // 如果服务1分钟内处于critical状态，则自动注销
		},
	}

	// 使用Consul客户端注册服务
	if err := global.ConsulClient.Agent().ServiceRegister(registration); err != nil {
		log.Fatalf("Add_Telegraf Error registering telegraf service with Consul:%v\n", err)
		return
	}

	log.Printf("Telegraf service %s registered successfully\n", telegrafID)
}
